from datetime import datetime, timedelta
from PySide6 import QtWidgets, QtCore, QtGui
from numpy import busday_count
from tushare import latest_content
from vnpy.event import Event
from vnpy.trader.constant import Exchange
from ..engine.portfolio_engine import PortfolioEngine
from ..engine.position_manager import PositionManager
from ..engine.asset_manager import AssetManager
from ..engine.trade_recorder import TradeRecorder
from ..advisor.engine import AdvisorTemplate
from ..strategy.template import StrategyTemplate
from ..event import EVENT_PORTFOLIO_UPDATE
from ..datafeed.data_loader import PortfolioDataLoader
from portfolio_trader.datafeed import data_loader

class PortfolioTraderWindow(QtWidgets.QWidget):
    """组合交易窗口"""
    
    def __init__(self, main_engine=None, event_engine=None):
        """构造函数"""
        super().__init__()
        
        self.main_engine = main_engine
        self.event_engine = event_engine
        
        # 获取组合交易引擎
        self.portfolio_engine = main_engine.get_engine("PortfolioEngine")
        
        self.setWindowTitle("组合交易")
        
        self.init_ui()
        self.showMaximized()  # 先显示窗口
        
        # 异步更新界面
        QtCore.QTimer.singleShot(100, self.update_gui)
        
    def init_ui(self):
        """初始化界面"""
        self.init_widgets()
        self.init_layouts()
        self.init_signals()
        self.load_collection_list()
        
        # 设置样式
        self.setStyleSheet("""
            /* 全局样式 */
            QWidget {
                font-family: Arial, sans-serif;
            }
            
            /* Tab样式 */
            QTabWidget::pane { 
                border: 1px solid #1E90FF;
                background: white;
            }
            QTabWidget::tab-bar {
                left: 5px;
            }
            QTabBar::tab {
                background: #F0F8FF;
                border: 1px solid #1E90FF;
                padding: 8px 12px;
                margin-right: 2px;
                min-width: 100px;
                font-size: 13px;
                color: #1E90FF;
            }
            QTabBar::tab:selected {
                background: #1E90FF;
                border-bottom-color: #1E90FF;
                color: white;
                font-weight: bold;
            }
            
            /* 按钮样式 */
            QPushButton {
                padding: 5px 10px;
                background-color: #1E90FF;
                color: white;
                border: none;
                border-radius: 3px;
            }
            QPushButton:hover {
                background-color: #4169E1;
            }
            QPushButton:pressed {
                background-color: #0000CD;
            }
            
            /* 工具栏按钮样式 */
            #toolbarButton {
                padding: 6px 12px;
                background-color: #1E90FF;
                color: white;
                border: none;
                border-radius: 3px;
            }
            #toolbarButton:hover {
                background-color: #4169E1;
            }
            #toolbarButton:pressed {
                background-color: #0000CD;
            }
        """)
        
    def init_widgets(self):
        """初始化控件"""
        # 创建Tab控件
        self.tab_widget = QtWidgets.QTabWidget()
        
        # 交易操作相关控件
        self.trading_group = QtWidgets.QGroupBox("交易操作")
        self.symbol_line = QtWidgets.QLineEdit()
        self.symbol_line.setPlaceholderText("输入股票代码")
        self.price_spin = QtWidgets.QDoubleSpinBox()
        self.price_spin.setRange(0, 1000000)
        self.price_spin.setDecimals(2)
        self.price_spin.setSingleStep(0.01)
        self.volume_spin = QtWidgets.QSpinBox()
        self.volume_spin.setRange(0, 1000000)
        self.volume_spin.setSingleStep(100)
        self.commission_spin = QtWidgets.QDoubleSpinBox()
        self.commission_spin.setRange(0, 0.1)
        self.commission_spin.setDecimals(4)
        self.commission_spin.setSingleStep(0.0001)
        self.commission_spin.setValue(0.0001)
        self.buy_button = QtWidgets.QPushButton("买入")
        self.sell_button = QtWidgets.QPushButton("卖出")
        
        # 持仓信息相关控件
        self.position_group = QtWidgets.QGroupBox("持仓信息")
        self.position_table = QtWidgets.QTableWidget()
        self.position_table.setColumnCount(11)
        self.position_table.setHorizontalHeaderLabels(["代码", "名称", "数量", "可用", "成本", "现价", "市值", "盈亏", "盈亏率(%)", "日盈亏", "日盈亏率(%)"])
        self.position_table.horizontalHeader().setStretchLastSection(True)
        
        # 量化信号相关控件
        self.strategy_group = QtWidgets.QGroupBox("量化信号")
        # 股票选择下拉菜单
        self.symbol_combo = QtWidgets.QComboBox()
        self.symbol_combo.setFixedWidth(200)
        # 信号显示表格
        self.signal_table = QtWidgets.QTableWidget()
        self.signal_table.setColumnCount(7)
        self.signal_table.setHorizontalHeaderLabels(["策略名称", "信号类型", "方向", "价格", "数量", "时间", "有效"])
        self.signal_table.horizontalHeader().setStretchLastSection(True)
        
        # 投资建议相关控件
        self.advisor_group = QtWidgets.QGroupBox("投资建议")
        self.advisor_combo = QtWidgets.QComboBox()
        # 持仓股建议表格
        self.position_advice_table = QtWidgets.QTableWidget()
        self.position_advice_table.setColumnCount(7)
        self.position_advice_table.setHorizontalHeaderLabels(["代码", "名称", "操作", "数量", "价格区间", "昨日收盘价", "理由"])
        self.position_advice_table.horizontalHeader().setStretchLastSection(True)
        # 收藏股建议表格
        self.collection_advice_table = QtWidgets.QTableWidget()
        self.collection_advice_table.setColumnCount(7)
        self.collection_advice_table.setHorizontalHeaderLabels(["代码", "名称", "操作", "数量", "价格区间", "昨日收盘价", "理由"])
        self.collection_advice_table.horizontalHeader().setStretchLastSection(True)
        
        # 交易记录相关控件
        self.trade_group = QtWidgets.QGroupBox("交易记录")
        self.trade_table = QtWidgets.QTableWidget()
        self.trade_table.setColumnCount(9)
        self.trade_table.setHorizontalHeaderLabels(["时间", "代码", "名称", "方向", "委托价", "成交价", "数量", "成交额", "手续费"])
        self.trade_table.horizontalHeader().setStretchLastSection(True)
        
        # 创建Tab页
        self.tab_portfolio = QtWidgets.QWidget()
        self.tab_trading = QtWidgets.QWidget()
        self.tab_strategy = QtWidgets.QWidget()
        self.tab_advisor = QtWidgets.QWidget()
        self.tab_collection = QtWidgets.QWidget()
        
        # 添加Tab页到Tab控件
        self.tab_widget.addTab(self.tab_portfolio, "组合概览")
        self.tab_widget.addTab(self.tab_trading, "交易操作")
        self.tab_widget.addTab(self.tab_collection, "股票收藏")
        self.tab_widget.addTab(self.tab_strategy, "量化信号")
        self.tab_widget.addTab(self.tab_advisor, "投资建议")
        self.collection_button = QtWidgets.QPushButton("股票收藏")
        self.collection_button.setObjectName("toolbarButton")
        self.collection_button.setFixedWidth(100)
        
        # 股票收藏区域
        self.collection_symbol_line = QtWidgets.QLineEdit()
        self.collection_symbol_line.setPlaceholderText("输入股票代码")
        self.add_collection_button = QtWidgets.QPushButton("添加收藏")
        self.remove_collection_button = QtWidgets.QPushButton("移除收藏")
        self.collection_list = QtWidgets.QTableWidget()
        self.collection_list.setColumnCount(4)
        self.collection_list.setHorizontalHeaderLabels(['股票代码', '股票名称','最新价格', '记录时间'])
        self.collection_list.horizontalHeader().setStretchLastSection(True)
        self.collection_list.setRowCount(0)
        self.strategy_name_combo = QtWidgets.QComboBox()
        self.strategy_name_combo.addItems(["AtrRsiStrategy", "MaStrategy", "BollChannelStrategy"])
        
        # 账户信息区域
        self.account_group = QtWidgets.QGroupBox("账户信息")
        self.total_asset_label = QtWidgets.QLabel("总资产: 0.00")
        self.available_label = QtWidgets.QLabel("可用资金: 0.00")
        self.market_value_label = QtWidgets.QLabel("持仓市值: 0.00")
        self.pnl_label = QtWidgets.QLabel("当日盈亏: 0.00")
        
        # 资金调整区域
        self.capital_group = QtWidgets.QGroupBox("资金调整")
        self.capital_spin = QtWidgets.QDoubleSpinBox()
        self.capital_spin.setRange(0, 1000000000)  # 设置范围
        self.capital_spin.setDecimals(2)  # 设置小数位数
        self.capital_spin.setSingleStep(1000)  # 设置步长
        self.add_capital_button = QtWidgets.QPushButton("增加资金")
        self.sub_capital_button = QtWidgets.QPushButton("减少资金")
    
    def init_layouts(self):
        """初始化布局"""
        # 账户信息布局
        account_layout = QtWidgets.QGridLayout()
        account_layout.addWidget(self.total_asset_label, 0, 0)
        account_layout.addWidget(self.available_label, 0, 1)
        account_layout.addWidget(self.market_value_label, 1, 0)
        account_layout.addWidget(self.pnl_label, 1, 1)
        self.account_group.setLayout(account_layout)
        
        # 资金调整布局
        capital_layout = QtWidgets.QVBoxLayout()
        capital_form_layout = QtWidgets.QFormLayout()
        capital_form_layout.addRow("调整金额:", self.capital_spin)
        capital_layout.addLayout(capital_form_layout)
        capital_button_layout = QtWidgets.QHBoxLayout()
        capital_button_layout.addWidget(self.add_capital_button)
        capital_button_layout.addWidget(self.sub_capital_button)
        capital_layout.addLayout(capital_button_layout)
        self.capital_group.setLayout(capital_layout)
        
        # 交易操作布局
        trading_layout = QtWidgets.QFormLayout()
        trading_layout.addRow("代码", self.symbol_line)
        trading_layout.addRow("价格", self.price_spin)
        trading_layout.addRow("数量", self.volume_spin)
        trading_layout.addRow("手续费率", self.commission_spin)
        button_layout = QtWidgets.QHBoxLayout()
        button_layout.addWidget(self.buy_button)
        button_layout.addWidget(self.sell_button)
        trading_layout.addRow(button_layout)
        self.trading_group.setLayout(trading_layout)
        
        # 持仓信息布局
        position_layout = QtWidgets.QVBoxLayout()
        position_layout.addWidget(self.position_table)
        self.position_group.setLayout(position_layout)
        
        # 交易记录布局
        trade_layout = QtWidgets.QVBoxLayout()
        trade_layout.addWidget(self.trade_table)
        self.trade_group.setLayout(trade_layout)

        # 量化信号布局
        strategy_layout = QtWidgets.QVBoxLayout()
        
        # 添加股票选择和刷新按钮
        symbol_layout = QtWidgets.QHBoxLayout()
        symbol_layout.addWidget(QtWidgets.QLabel("选择股票:"))
        symbol_layout.addWidget(self.symbol_combo)
        symbol_layout.addStretch()
        
        strategy_layout.addLayout(symbol_layout)
        strategy_layout.addWidget(self.signal_table)
        self.strategy_group.setLayout(strategy_layout)
        
        # 投资建议布局
        advisor_layout = QtWidgets.QVBoxLayout()
        # 添加持仓股表头
        position_label = QtWidgets.QLabel("持仓股建议")
        position_label.setStyleSheet("font-weight: bold;")
        advisor_layout.addWidget(position_label)
        advisor_layout.addWidget(self.position_advice_table)
        # 添加收藏股表头
        collection_label = QtWidgets.QLabel("收藏股建议")
        collection_label.setStyleSheet("font-weight: bold;")
        advisor_layout.addWidget(collection_label)
        advisor_layout.addWidget(self.collection_advice_table)
        
        self.advisor_group.setLayout(advisor_layout)
        
        # 设置各个Tab页的布局
        # 组合概览Tab
        portfolio_layout = QtWidgets.QVBoxLayout()
        portfolio_layout.addWidget(self.account_group)
        portfolio_layout.addWidget(self.capital_group)
        portfolio_layout.addWidget(self.position_group)
        self.tab_portfolio.setLayout(portfolio_layout)
        
        # 交易操作Tab
        trading_tab_layout = QtWidgets.QVBoxLayout()
        trading_tab_layout.addWidget(self.trading_group)
        trading_tab_layout.addWidget(self.trade_group)
        self.tab_trading.setLayout(trading_tab_layout)
        
        # 量化信号Tab
        strategy_tab_layout = QtWidgets.QVBoxLayout()
        strategy_tab_layout.addWidget(self.strategy_group)
        self.tab_strategy.setLayout(strategy_tab_layout)
        
        # 投资建议Tab
        advisor_tab_layout = QtWidgets.QVBoxLayout()
        advisor_tab_layout.addWidget(self.advisor_group)
        self.tab_advisor.setLayout(advisor_tab_layout)
        
        # 股票收藏Tab
        collection_layout = QtWidgets.QVBoxLayout()
        # 输入布局
        collection_input_layout = QtWidgets.QHBoxLayout()
        collection_input_layout.addWidget(self.collection_symbol_line)
        collection_input_layout.addWidget(self.add_collection_button)
        collection_input_layout.addWidget(self.remove_collection_button)
        collection_layout.addLayout(collection_input_layout)
        collection_layout.addWidget(self.collection_list)
        self.tab_collection.setLayout(collection_layout)

        # 策略选择
        collection_setting_layout = QtWidgets.QFormLayout()
        collection_setting_layout.addRow("选择策略:", self.strategy_name_combo)
        
        # 添加到主布局
        main_layout = QtWidgets.QVBoxLayout()
        main_layout.addWidget(self.tab_widget)
        self.setLayout(main_layout)
        
    def init_signals(self):
        """初始化信号"""
        self.buy_button.clicked.connect(self.buy)
        self.sell_button.clicked.connect(self.sell)
        self.add_capital_button.clicked.connect(self.add_capital)
        self.sub_capital_button.clicked.connect(self.sub_capital)
        
        # 股票收藏相关信号
        self.add_collection_button.clicked.connect(self.add_collection)
        self.remove_collection_button.clicked.connect(self.remove_collection)
        
        # 量化信号相关信号
        self.symbol_combo.currentTextChanged.connect(self.refresh_signals)
        
        # 注册事件监听
        self.event_engine.register(EVENT_PORTFOLIO_UPDATE, self.process_portfolio_event)
        
    def buy(self):
        """买入操作"""
        symbol = self.symbol_line.text().strip()
        price = round(self.price_spin.value(), 2)  # 强制保留两位小数
        volume = self.volume_spin.value()
        
        if not symbol:
            QtWidgets.QMessageBox.warning(self, "错误", "请输入股票代码")
            return

        if price <= 0:
            QtWidgets.QMessageBox.warning(self, "错误", "价格必须大于0")
            return

        if not all([symbol, price, volume]):
            QtWidgets.QMessageBox.warning(self, "提示", "请输入完整的交易信息")
            return
        
        buy_result = self.portfolio_engine.buy(symbol, price, volume)
        if buy_result == "Success":
            QtWidgets.QMessageBox.information(self, "成功", "买入委托已提交")
            self.update_gui()
        elif buy_result == "NoEnoughMoney":
            available_capital = self.portfolio_engine.asset_manager.get_available_capital()
            QtWidgets.QMessageBox.warning(self, "失败", f"资金不足，当前资金为{available_capital}")
            print(available_capital)
        elif buy_result == "Cannot get current price":
            QtWidgets.QMessageBox.warning(self, "失败", "无法获取当前价格")
                  
    def sell(self):
        """卖出操作"""
        symbol = self.symbol_line.text().strip()
        price = round(self.price_spin.value(), 2)  # 强制保留两位小数
        volume = self.volume_spin.value()
        
        if not symbol:
            QtWidgets.QMessageBox.warning(self, "错误", "请输入股票代码")
            return

        if not all([symbol, price, volume]):
            QtWidgets.QMessageBox.warning(
                self,
                "提示",
                "请输入完整的交易信息"
            )
            return

        # 检查当前持仓
        position = self.portfolio_engine.position_manager.get_position(symbol)
        if not position or position.get("available", 0) < volume:
            QtWidgets.QMessageBox.warning(self, "失败", "持仓数量不足")
            return

        # 执行卖出
        if self.portfolio_engine.sell(symbol, price, volume):
            QtWidgets.QMessageBox.information(
                self,
                "成功",
                "卖出委托已提交"
            )
            self.update_gui()
        else:
            QtWidgets.QMessageBox.warning(
                self,
                "失败",
                "卖出操作失败"
            )

    def update_gui(self):
        """更新界面"""
        # 更新账户信息
        account = self.portfolio_engine.asset_manager.get_account()
        self.total_asset_label.setText(f"总资产: {account['total_asset']:.2f}")
        self.available_label.setText(f"可用资金: {account['available']:.2f}")
        self.market_value_label.setText(f"持仓市值: {account['market_value']:.2f}")
        self.pnl_label.setText(f"当日盈亏: {account['daily_pnl']:.2f}")
        
        # 更新信号显示
        self.refresh_signals()
        
        # 更新持仓表格
        self.update_positions()
        
        # 更新交易记录
        self.update_trades()
        
        # 更新持仓和收藏股票建议
        self.update_advice()
        
    def load_collection_list(self):
        """加载收藏列表"""
        data_loader = self.portfolio_engine.data_loader
        stock_collection = self.portfolio_engine.stock_collection_manager.get_collection()
        self.collection_list.setRowCount(len(stock_collection))

        for idx, symbol in enumerate(stock_collection):
            name = data_loader.get_stock_name(symbol)
            latest_price = data_loader.get_latest_daily_data(symbol).close_price
            latest_date = data_loader.get_latest_local_date(symbol, "daily").strftime('%Y-%m-%d')
            self.collection_list.setItem(idx, 0, QtWidgets.QTableWidgetItem(symbol))
            self.collection_list.setItem(idx, 1, QtWidgets.QTableWidgetItem(name))
            self.collection_list.setItem(idx, 2, QtWidgets.QTableWidgetItem(f"{latest_price:.2f}"))
            self.collection_list.setItem(idx, 3, QtWidgets.QTableWidgetItem(latest_date))
            
            # 设置文本对齐方式
            for col in range(self.position_table.columnCount()):
                item = self.position_table.item(idx, col)
                if item:
                    item.setTextAlignment(QtCore.Qt.AlignCenter)
        
    def refresh_signals(self):
        """刷新量化信号"""
        symbol = self.symbol_combo.currentText()
        if not symbol:
            return
        
        # 显示进度对话框
        progress_dialog = QtWidgets.QProgressDialog("正在刷新信号...", "取消", 0, 0, self)
        progress_dialog.setWindowTitle("请稍候")
        progress_dialog.setWindowModality(QtCore.Qt.WindowModal)
        progress_dialog.setCancelButton(None)
        progress_dialog.show()
        
        # 获取信号数据
        signal_manager = self.portfolio_engine.signal_manager
        signals = signal_manager.get_latest_trading_day_signals()
        
        if symbol not in signals:
            progress_dialog.close()
            return
            
        # 更新表格
        signal_data = signals[symbol]
        self.signal_table.setRowCount(len(signal_data))
        
        for row, (strategy_name, signal) in enumerate(signal_data.items()):
            self.signal_table.setItem(row, 0, QtWidgets.QTableWidgetItem(strategy_name))
            self.signal_table.setItem(row, 1, QtWidgets.QTableWidgetItem(signal["signal_type"]))
            self.signal_table.setItem(row, 2, QtWidgets.QTableWidgetItem(signal["direction"]))
            self.signal_table.setItem(row, 3, QtWidgets.QTableWidgetItem(f"{signal['price']:.2f}"))
            self.signal_table.setItem(row, 4, QtWidgets.QTableWidgetItem(str(signal["volume"])))
            self.signal_table.setItem(row, 5, QtWidgets.QTableWidgetItem(signal["datetime"]))
            self.signal_table.setItem(row, 6, QtWidgets.QTableWidgetItem("是" if signal["is_valid"] else "否"))
            
            # 设置文本对齐方式
            for col in range(self.signal_table.columnCount()):
                item = self.signal_table.item(row, col)
                if item:
                    item.setTextAlignment(QtCore.Qt.AlignCenter)
        # 关闭进度对话框
        progress_dialog.close()
            
    def update_advice(self):
        """更新持仓和收藏股票的建议"""
        positions = self.portfolio_engine.position_manager.get_positions()
        collections = self.portfolio_engine.stock_collection_manager.get_collection()
        data_loader = self.portfolio_engine.data_loader
        advisor = self.portfolio_engine.advisor
        
        # 更新股票选择下拉菜单
        self.symbol_combo.clear()
        self.symbol_combo.addItems(list(positions.keys()))
        
        # 设置持仓股建议表格
        self.position_advice_table.setRowCount(len(positions))
        
        # 遍历持仓生成建议
        for idx, (symbol, pos) in enumerate(positions.items()):
            advice = advisor.generate_advice_for_stock(symbol, strategies=["AtrRsiStrategy"])
            decisions = advice.get('decisions', [])
            latest_price = data_loader.get_latest_daily_data(symbol).close_price

            if decisions:
                decision = decisions[0]
                # 设置表格内容
                self.position_advice_table.setItem(idx, 0, QtWidgets.QTableWidgetItem(symbol))
                self.position_advice_table.setItem(idx, 1, QtWidgets.QTableWidgetItem(pos.get('name', '')))  # 名称
                self.position_advice_table.setItem(idx, 2, QtWidgets.QTableWidgetItem(decision.action))
                self.position_advice_table.setItem(idx, 3, QtWidgets.QTableWidgetItem(str(decision.quantity)))
                self.position_advice_table.setItem(idx, 4, QtWidgets.QTableWidgetItem(str(decision.price_range)))
                self.position_advice_table.setItem(idx, 5, QtWidgets.QTableWidgetItem(f"{latest_price:.2f}"))
                self.position_advice_table.setItem(idx, 6, QtWidgets.QTableWidgetItem(decision.reason))  
            else:
                # 今日没有操作
                self.position_advice_table.setItem(idx, 0, QtWidgets.QTableWidgetItem(symbol))
                self.position_advice_table.setItem(idx, 1, QtWidgets.QTableWidgetItem(pos.get('name', '')))
                self.position_advice_table.setItem(idx, 2, QtWidgets.QTableWidgetItem("建议持仓"))
                self.position_advice_table.setItem(idx, 3, QtWidgets.QTableWidgetItem("/"))
                self.position_advice_table.setItem(idx, 4, QtWidgets.QTableWidgetItem("/"))
                self.position_advice_table.setItem(idx, 5, QtWidgets.QTableWidgetItem(f"{latest_price:.2f}"))
                self.position_advice_table.setItem(idx, 6, QtWidgets.QTableWidgetItem("策略建议今日持仓"))
            # 设置文本对齐方式
            for col in range(self.position_advice_table.columnCount()):
                item = self.position_advice_table.item(idx, col)
                if item:
                    item.setTextAlignment(QtCore.Qt.AlignCenter)
                    
        # 设置收藏股建议表格
        self.collection_advice_table.setRowCount(len(collections))
        
        # 遍历收藏股票生成建议
        for idx, symbol in enumerate(collections):
            name = data_loader.get_stock_name(symbol)
            advice = advisor.generate_advice_for_stock(symbol, strategies=["AtrRsiStrategy"])
            decisions = advice.get('decisions', [])
            latest_price = data_loader.get_latest_daily_data(symbol).close_price

            if decisions:
                decision = decisions[0]
                # 设置表格内容
                self.collection_advice_table.setItem(idx, 0, QtWidgets.QTableWidgetItem(symbol))
                self.collection_advice_table.setItem(idx, 1, QtWidgets.QTableWidgetItem(name))
                self.collection_advice_table.setItem(idx, 2, QtWidgets.QTableWidgetItem(decision.action))
                self.collection_advice_table.setItem(idx, 3, QtWidgets.QTableWidgetItem(str(decision.quantity)))
                self.collection_advice_table.setItem(idx, 4, QtWidgets.QTableWidgetItem(str(decision.price_range)))
                self.collection_advice_table.setItem(idx, 5, QtWidgets.QTableWidgetItem(f"{latest_price:.2f}"))
                self.collection_advice_table.setItem(idx, 6, QtWidgets.QTableWidgetItem(decision.reason))
            else:
                # 今日没有操作
                self.collection_advice_table.setItem(idx, 0, QtWidgets.QTableWidgetItem(symbol))
                self.collection_advice_table.setItem(idx, 1, QtWidgets.QTableWidgetItem(name))
                self.collection_advice_table.setItem(idx, 2, QtWidgets.QTableWidgetItem("建议观望"))
                self.collection_advice_table.setItem(idx, 3, QtWidgets.QTableWidgetItem("/"))
                self.collection_advice_table.setItem(idx, 4, QtWidgets.QTableWidgetItem("/"))
                self.collection_advice_table.setItem(idx, 5, QtWidgets.QTableWidgetItem(f"{latest_price:.2f}"))
                self.collection_advice_table.setItem(idx, 6, QtWidgets.QTableWidgetItem("策略建议今日观望"))
            # 设置文本对齐方式
            for col in range(self.collection_advice_table.columnCount()):
                item = self.collection_advice_table.item(idx, col)
                if item:
                    item.setTextAlignment(QtCore.Qt.AlignCenter)
                    
    def update_positions(self):
        """更新持仓表格"""
        positions = self.portfolio_engine.position_manager.get_positions()
        self.position_table.setRowCount(len(positions))
        
        for idx, (symbol, pos) in enumerate(positions.items()):
            
            # 设置表格内容
            self.position_table.setItem(idx, 0, QtWidgets.QTableWidgetItem(symbol))  # 代码
            self.position_table.setItem(idx, 1, QtWidgets.QTableWidgetItem(pos.get('name', '')))  # 名称
            self.position_table.setItem(idx, 2, QtWidgets.QTableWidgetItem(str(pos.get('volume', 0))))  # 数量
            self.position_table.setItem(idx, 3, QtWidgets.QTableWidgetItem(str(pos.get('available', 0))))  # 可用
            self.position_table.setItem(idx, 4, QtWidgets.QTableWidgetItem(f"{pos.get('cost', 0.0):.2f}"))  # 成本
            self.position_table.setItem(idx, 5, QtWidgets.QTableWidgetItem(f"{pos.get('current_price', 0.0):.2f}"))  # 现价
            self.position_table.setItem(idx, 6, QtWidgets.QTableWidgetItem(f"{pos.get('market_value', 0.0):.2f}"))  # 市值
            self.position_table.setItem(idx, 7, QtWidgets.QTableWidgetItem(f"{pos.get('pnl', 0.0):.2f}"))  # 盈亏
            self.position_table.setItem(idx, 8, QtWidgets.QTableWidgetItem(f"{pos.get('pnl_pct', 0.0):.2f}"))  # 盈亏率
            self.position_table.setItem(idx, 9, QtWidgets.QTableWidgetItem(f"{pos.get('daily_pnl', 0.0):.2f}"))  # 日盈亏
            self.position_table.setItem(idx, 10, QtWidgets.QTableWidgetItem(f"{pos.get('daily_pnl_pct', 0.0):.2f}"))  # 日盈亏率
            
            # 设置文本对齐方式
            for col in range(self.position_table.columnCount()):
                item = self.position_table.item(idx, col)
                if item:
                    item.setTextAlignment(QtCore.Qt.AlignCenter)
        
    def update_trades(self):
        """更新交易记录表格"""
        trades = self.portfolio_engine.trade_recorder.get_trades()
        trades = sorted(trades, key=lambda x: x["time"], reverse=True)  # 按时间倒序排序
        self.trade_table.setRowCount(len(trades))
        
        for idx, trade in enumerate(trades):
            self.trade_table.setItem(idx, 0, QtWidgets.QTableWidgetItem(trade["time"]))
            self.trade_table.setItem(idx, 1, QtWidgets.QTableWidgetItem(trade["symbol"]))
            self.trade_table.setItem(idx, 2, QtWidgets.QTableWidgetItem(trade["name"]))
            self.trade_table.setItem(idx, 3, QtWidgets.QTableWidgetItem(trade["direction"]))
            self.trade_table.setItem(idx, 4, QtWidgets.QTableWidgetItem(f"{trade['order_price']:.2f}"))
            self.trade_table.setItem(idx, 5, QtWidgets.QTableWidgetItem(f"{trade['trade_price']:.2f}"))
            self.trade_table.setItem(idx, 6, QtWidgets.QTableWidgetItem(str(trade["volume"])))
            self.trade_table.setItem(idx, 7, QtWidgets.QTableWidgetItem(f"{trade['amount']:.2f}"))
            self.trade_table.setItem(idx, 8, QtWidgets.QTableWidgetItem(f"{trade['commission']:.2f}"))

            # 设置文本对齐方式
            for col in range(self.position_table.columnCount()):
                item = self.position_table.item(idx, col)
                if item:
                    item.setTextAlignment(QtCore.Qt.AlignCenter)

    def add_capital(self):
        """增加资金"""
        amount = self.capital_spin.value()
        if amount <= 0:
            QtWidgets.QMessageBox.warning(
                self,
                "提示",
                "请输入正确的金额"
            )
            return
        
        if self.portfolio_engine.adjust_capital(amount):
            QtWidgets.QMessageBox.information(
                self,
                "成功",
                f"成功增加资金 {amount:.2f}"
            )
            self.update_gui()
        else:
            QtWidgets.QMessageBox.warning(
                self,
                "失败",
                "增加资金失败"
            )
    
    def sub_capital(self):
        """减少资金"""
        amount = self.capital_spin.value()
        if amount <= 0:
            QtWidgets.QMessageBox.warning(
                self,
                "提示",
                "请输入正确的金额"
            )
            return
        
        if self.portfolio_engine.adjust_capital(-amount):
            QtWidgets.QMessageBox.information(
                self,
                "成功",
                f"成功减少资金 {amount:.2f}"
            )
            self.update_gui()
        else:
            QtWidgets.QMessageBox.warning(
                self,
                "失败",
                "可用资金不足"
            )

    def process_portfolio_event(self, event: Event):
        """处理组合更新事件"""
        self.update_gui()
        
    def add_collection(self):
        """添加股票到收藏列表"""
        symbol = self.collection_symbol_line.text().strip()
        
        # 情况1：空输入或纯空格输入
        if not symbol:
            QtWidgets.QMessageBox.warning(
                self, 
                "添加失败",
                "请输入有效的股票代码"
            )
            return
            
        # 使用StockCollection类验证股票代码格式
        if not self.portfolio_engine.stock_collection_manager.is_valid_symbol(symbol):
            QtWidgets.QMessageBox.warning(
                self,
                "代码格式错误",
                "股票代码必须为6位数字且符合以下规则：\n"
                "沪市：600/601/603/688开头\n"
                "深市：000/002/300开头"
            )
            return

        # 使用StockCollection类添加收藏
        if self.portfolio_engine.stock_collection_manager.add_to_collection(symbol):
            # 更新界面
            self.load_collection_list()
            
            QtWidgets.QMessageBox.information(
                self, 
                "添加成功",
                f"已将 {symbol} 添加到收藏列表"
            )
        else:
            QtWidgets.QMessageBox.information(
                self, 
                "添加提示",
                f"{symbol} 已在收藏列表中"
            )
    
    def remove_collection(self):
        """从收藏列表中移除股票"""
        selected_items = self.collection_list.selectedItems()
        if not selected_items:
            QtWidgets.QMessageBox.warning(
                self, 
                "移除失败",
                "请先选择要移除的股票"
            )
            return
            
        symbol = selected_items[0].text()
        
        # 使用StockCollection类移除收藏
        if self.portfolio_engine.stock_collection_manager.remove_from_collection(symbol):
            # 更新界面
            self.load_collection_list()
            
            QtWidgets.QMessageBox.information(
                self, 
                "移除成功",
                f"已将 {symbol} 从收藏列表中移除"
            )
        else:
            QtWidgets.QMessageBox.warning(
                self, 
                "移除失败",
                f"{symbol} 不在收藏列表中"
            )
